package com.cdzs.twocamera;

import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.RelativeLayout;

import com.sanquan.boardcomm.DoorAccessCommManager;
import com.sanquan.boardcomm.GpioController;
import com.serenegiant.common.BaseActivity;

import java.io.File;
import java.io.IOException;

public class VideoActivity extends BaseActivity {

    //==================== 视频播放 ===============================
    private boolean isPause;
    private MediaPlayer player;//媒体播放器
    private SurfaceView sfvAdvertising;//能够播放图像的控件
    private SurfaceHolder holderOfAdvertising;
    private int surfaceWidth;
    private int surfaceHeight;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_video);

        sfvAdvertising = findViewById(R.id.sfv_advertising);
        holderOfAdvertising = sfvAdvertising.getHolder();
        holderOfAdvertising.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        holderOfAdvertising.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                //为了避免图像控件还没有创建成功，用户就开始播放视频，造成程序异常，所以在创建成功后才使播放按钮可点击
                play();

                if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                    surfaceWidth = sfvAdvertising.getWidth();
                    surfaceHeight = sfvAdvertising.getHeight();
                } else {
                    surfaceWidth = sfvAdvertising.getHeight();
                    surfaceHeight = sfvAdvertising.getWidth();
                }

            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
                Log.d("zhangdi", "surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
                //当程序没有退出，但不在前台运行时，因为surfaceview很耗费空间，所以会自动销毁，
                // 这样就会出现当你再次点击进程序的时候点击播放按钮，声音继续播放，却没有图像
                //为了避免这种不友好的问题，简单的解决方式就是只要surfaceview销毁，我就把媒体播放器等
                //都销毁掉，这样每次进来都会重新播放，当然更好的做法是在这里再记录一下当前的播放位置，
                //每次点击进来的时候把位置赋给媒体播放器，很简单加个全局变量就行了。
                if (player != null) {
                    stop();
                }
            }
        });
    }


    private void play() {

        if (isPause) {//如果是暂停状态下播放，直接start
            isPause = false;
            player.start();
            return;
        }

        try {
            player = new MediaPlayer();
//            player.setDataSource("http://vf1.mtime.cn/Video/2015/03/20/mp4/150320094140850937_480.mp4");
            player.setDataSource(Environment.getExternalStorageDirectory().getPath() + File.separator + "twoCameraCrash" + File.separator + "video.mp4");
            player.setDisplay(holderOfAdvertising);//将影像播放控件与媒体播放控件关联起来

            player.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
                @Override
                public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
                    int videoWidth = player.getVideoWidth();
                    int videoHeight = player.getVideoHeight();

                    //根据视频尺寸去计算->视频可以在sufaceView中放大的最大倍数。
                    float max;
                    if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                        //竖屏模式下按视频宽度计算放大倍数值
                        max = Math.max((float) videoWidth / (float) surfaceWidth, (float) videoHeight / (float) surfaceHeight);
                    } else {
                        //横屏模式下按视频高度计算放大倍数值
                        max = Math.max(((float) videoWidth / (float) surfaceHeight), (float) videoHeight / (float) surfaceWidth);
                    }

                    //视频宽高分别/最大倍数值 计算出放大后的视频尺寸
                    videoWidth = (int) Math.ceil((float) videoWidth / max);
                    videoHeight = (int) Math.ceil((float) videoHeight / max);

                    //无法直接设置视频尺寸，将计算出的视频尺寸设置到surfaceView 让视频自动填充。
                    sfvAdvertising.setLayoutParams(new RelativeLayout.LayoutParams(videoWidth, videoHeight));
                }
            });

            player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {//视频播放完成后，释放资源
                    stop();
//                    Intent intent = new Intent(VideoActivity.this, MainActivitySurface.class);
//                    startActivity(intent);
                    finish();
                }
            });

            player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //媒体播放器就绪后，设置进度条总长度，开启计时器不断更新进度条，播放视频
                    Log.d("zhangdi", "onPrepared");
                    player.start();
                }
            });

            player.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stop() {
        isPause = false;
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("keyCode", "keyCode:" + keyCode);

        if (keyCode == DoorAccessCommManager.KEYCODE_INFRARED_ON) {
            stop();
            finish();
        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }

        return super.onKeyDown(keyCode, event);

    }

}
